import { message, Modal } from 'antd';
import request from 'axios';

/**
 * @description: 格式化参数
 * @param {object} params
 */
export const formatData = (params = {}) => {
  const formdata = new FormData();
  Object.keys(params).map(key => formdata.append(key, params[key]));
  return formdata;
};

/**
 * @description: 导出excel表 (POST)
 * @param {string} url 请求地址
 * @param {object} params 参数
 * @param {function} cb 回调函数
 */
export function exportExcel(url, params = {}, cb) {
  message.loading('导出数据中');
  return request(url, {
    method: 'POST',
    body: formatData(params),
    // 1、只能用在 ‘PUT’, ‘POST’ 和 ‘PATCH’ 这几个请求方法
    // 2、后面数组中的函数必须返回一个字符串，或 ArrayBuffer，或 Stream
    transformRequest: [
      res => {
        let result = '';
        Object.keys(res).forEach(key => {
          if (!Object.is(res[key], undefined) && !Object.is(res[key], null)) {
            result += `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}&`;
          }
        });
        return result;
      },
    ],
    responseType: 'blob',
  })
    .then(r => {
      const content = r;
      const blob = new Blob([content]);
      const fileName = `${params.name ? params.name : new Date().getTime()}_导出结果.xlsx`;
      if ('download' in document.createElement('a')) {
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        throw r;
        // eslint-disable-next-line no-unreachable
        navigator.msSaveBlob(blob, fileName);
      }
    })
    .catch(r => {
      console.error(r);
      message.error('导出失败');
    })
    .finally(() => {
      cb && cb();
    });
}

/**
 * @description: 导出excel表 (GET)
 * @param {string} url 请求地址
 * @param {object} params 参数
 * @param {function} cb 回调函数
 */
export function exportTableExcel(url, params = {}) {
  message.loading('导出数据中');
  return request(url, {
    method: 'GET',
    params,
    responseType: 'blob',
  })
    .then(r => {
      const content = r;
      const blob = new Blob([content]);
      const fileName = `${params.name ? params.name : new Date().getTime()}_导出结果.xlsx`;
      if ('download' in document.createElement('a')) {
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        throw r;
        // eslint-disable-next-line no-unreachable
        navigator.msSaveBlob(blob, fileName);
      }
    })
    .catch(r => {
      console.error(r);
      message.error('导出失败');
    });
}

/**
 * @description: 导出excel表 (POST, 参数以JSON格式)
 * @param {string} url 请求地址
 * @param {object} params 参数
 * @param {function} cb 回调函数
 */
export function exportExcelWithJson(url, params, cb) {
  message.loading('导出数据中');
  return request(url, {
    method: 'POST',
    body: JSON.stringify(params),
    headers: {
      'content-type': 'application/json',
    },
    transformRequest: [
      res => {
        let result = '';
        Object.keys(res).forEach(key => {
          if (!Object.is(res[key], undefined) && !Object.is(res[key], null)) {
            result += `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}&`;
          }
        });
        return result;
      },
    ],
    responseType: 'blob',
  })
    .then(r => {
      const content = r;
      const blob = new Blob([content]);
      const fileName = `${params.name ? params.name : new Date().getTime()}_导出结果.xlsx`;
      if ('download' in document.createElement('a')) {
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        throw r;
        // eslint-disable-next-line no-unreachable
        navigator.msSaveBlob(blob, fileName);
      }
    })
    .catch(r => {
      console.error(r);
      message.error('导出失败');
    })
    .finally(() => {
      cb && cb();
    });
}

/**
 * @description: 导出word
 * @param {string} url 请求地址
 * @param {object} params 参数
 * @param {function} cb 回调函数
 */
export function exportWord(url, params = {}, cb) {
  message.loading('导出数据中');
  return request(url, {
    method: 'GET',
    params,
    responseType: 'blob',
  })
    .then(res => {
      const data = res;
      const filename = params.uploadPath;
      if (data) {
        const a = document.createElement('a');
        const blob = new Blob([data], { type: 'application/vnd.ms-excel' }); // 创建URL
        const blobUrl = window.URL.createObjectURL(blob);
        a.download = filename;
        a.href = blobUrl;
        document.body.appendChild(a); // 下载文件
        a.click(); // 释放内存
        URL.revokeObjectURL(blobUrl);
        document.body.removeChild(a);
      } else {
        console.error('文件下载错误');
      }
    })
    .catch(() => {
      message.error('导出失败');
    })
    .finally(() => {
      cb && cb();
    });
}

/**
 * @description: 批量删除（支持单挑或多条）
 * @param {object} row 单条记录
 * @param {array} selectedRowKeys 多条记录
 * @param {function} deleteRequest 删除接口
 * @param {function} callback 回调函数
 */
export function batchDelete(row, selectedRowKeys, deleteRequest, callback) {
  const id = row ? row.id : (selectedRowKeys || []).join(',');
  if (id) {
    Modal.confirm({
      title: '确定删除所选中的记录?',
      content: '当您点击确定按钮后，这些记录将会被彻底删除',
      centered: true,
      cancelText: '取消',
      okText: '确定',
      onOk: async () => {
        try {
          const res = await deleteRequest(id);
          if (res.success) {
            message.success('删除成功!');
            callback();
          } else {
            message.error(res.message);
          }
        } catch (err) {
          message.error('删除失败!');
        }
      },
    });
  } else {
    message.warn('请选择需要删除的记录');
  }
}

/**
 * @description: 由值找键
 * @param {*} value 待匹配值
 * @param {*} dictByGroup 匹配对象
 */
export function getKeyByValue(value, dictByGroup) {
  let valueKey = '';
  Object.keys(dictByGroup).forEach(key => {
    if (dictByGroup[key] == value) valueKey = key;
  });
  return valueKey;
}

/**
 * @description: ajax下载
 * @param {*} url 地址
 * @param {*} name 文件名
 */
export function download(url, name) {
  const x = new window.XMLHttpRequest();
  x.open('GET', url, true);
  x.responseType = 'blob';
  x.onload = () => {
    const blobUrl = window.URL.createObjectURL(x.response);
    const a = document.createElement('a');
    a.href = url;
    a.download = name;
    a.click();
    URL.revokeObjectURL(blobUrl);
    document.body.removeChild(a);
  };
  x.send();
}

/**
 * @description: 下载二维码
 * @param {*} id canvas容器id
 * @param {*} name 文件名
 */
export function handleDownLoadQRCode(id, name) {
  // 先获取要下载的二维码
  const Qr = document.getElementById(id);
  // 把canvas的数据改成base64的格式
  const canvasUrl = Qr.toDataURL('image/png');
  const myBlob = dataURLtoBlob(canvasUrl);
  const myUrl = URL.createObjectURL(myBlob); // 创建blob下载地址
  downloadFile(myUrl, name || '自定义下载');
  URL.revokeObjectURL(myUrl);
}
/**
 * @description: 下载文件
 * @param {*} url 文件地址
 * @param {*} name 文件名
 */
export function downloadFile(url, name) {
  // 创建a标签用于下载
  const a = document.createElement('a');
  a.setAttribute('href', url);
  a.setAttribute('download', name);
  a.setAttribute('target', '_blank');
  const clickEvent = document.createEvent('MouseEvents');
  clickEvent.initEvent('click', true, true); // 模拟点击
  a.dispatchEvent(clickEvent);
}

/**
 * @description: base64转文件
 * @param {*} dataurl base64
 */
export function dataURLtoBlob(dataurl) {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}
